<template>
  <div>
    <el-dialog title="表单" v-model="visible" v-bind="$attrs" :close-on-click-modal="false" :close-on-press-escape="false">
      <template #default>
        <hf-form ref="formRef" :options="options" @on-upload-change="uploadChange">
          <template #footer="{form, data}">
            <el-button @click="cancel(form)">取消</el-button>
            <el-button type="primary" @click="confirm(form, data)">确认</el-button>
          </template>
        </hf-form>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, FormInstance, UploadFile } from 'element-plus'
import { ref, watch, PropType } from 'vue'
import { FormOptions } from '../form/types'

let props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  options: {
    type: Array as PropType<FormOptions[]>,
    require: true,
  },
})

let emits = defineEmits(['update:visible', 'update:options'])
// visible 更新
watch(
  () => props.visible,
  (cur, pre) => {
    emits('update:visible', cur)
  },
)

// 处理  hf-form
let formRef = ref() // hf-form
let uploadChange = (prop: string, uploadFile: UploadFile, uploadFiles: UploadFile[]) => {
  console.log(prop)
}

// 重置
let cancel = (form: FormInstance) => {
  // 重置后下拉框里的数据也会被清空 ???
  formRef.value.resetForm()
  // emits('update:visible', false)
  console.log(props.options)
}
// 自定义表单提交动作:如 http post等
let confirm = (form: FormInstance, data: any) => {
  console.log('data:', data)
  form.validate(valid => {
    if (valid) {
      // 数据提交
      ElMessage.success('提交成功')
      emits('update:visible', false)
    } else {
      ElMessage.error('验证失败')
    }
  })
}
</script>

<style></style>
